﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using SmugMugModel;

namespace SmugMugToLiveWriter
{
    public partial class GetSmugMugImages : Form
    {
        private Site mySite = new Site();
        private MyUser CurrentUser = null;
        private bool IsAlreadyLogged = false;
        private bool UserAlreadyLogged = false;
        private string mytoSend = string.Empty;
        public string toSend
        {
            get { return mytoSend; }
            set { mytoSend = value; }
        }


        /// <summary>
        /// Log in to SmugMug using the LogInWithHash, if you have the UserId and PasswordHash stored in the registries
        /// </summary>
        /// <returns></returns>
        private bool SmugMugLogInWithHash()
        {
            object UserId = Application.UserAppDataRegistry.GetValue("UserId");
            object Password = Application.UserAppDataRegistry.GetValue("Password");
            if ((UserId == null) || string.IsNullOrEmpty((string)Password))
                return false;
            try
            {
                CurrentUser = mySite.Login((int)UserId, (string)Password);
            }
            catch (SmugMugException sme)
            {
                MessageBox.Show(sme.Message);
                CurrentUser = null;
                return false;
            }
            IsAlreadyLogged = true;
            return true;
        }

        /// <summary>
        /// Log in to SmugMug using a UserName and Password
        /// </summary>
        private void SmugMugLogIn()
        {
            LogIn li = new LogIn();
            DialogResult dr;
            // Try to login as long as there is no valid SmugMug user (the user didn't provide valid user name and password), and the Ok button was pressed
            do
            {
                dr = li.ShowDialog(this);
            }
            while ((dr == DialogResult.OK) && (li.user == null));
            
            // The log in was successful or/and the Cancel button was pushed
            // If the log in was succesful, it returns a user which you have to  make the current user, for the appropriate gallery to be loaded
            if (li.user != null)
            {
                CurrentUser = li.user;
                IsAlreadyLogged = true;
            }
            // If the Cancel button was pushed, if there was a user already logged in, just reload his galleries, if not, exit the app as you have no user logged in
            else
            {
                if (IsAlreadyLogged == true)
                {
                    MessageBox.Show("The user wasn't changed");
                    UserAlreadyLogged = true;
                }
                else
                {
                    MessageBox.Show("The login wasn't successful! The plug-in will now close!");
                    Close();
                }
            }            
        }


        /// <summary>
        /// Chooses the right URL for the given picture based on its size
        /// </summary>
        /// <param name="PictureSize"></param>
        /// <param name="Picture"></param>
        /// <returns>The Picture's URL</returns>
        private string SetImageURL(string ImageSize, SmugMugModel.Image myImage)
        {
            string myImageURL = string.Empty;
            // Validates that the picture object is not null
            if (myImage == null)
                return string.Empty;
            switch (ImageSize)
            {
                case "Large": myImageURL = myImage.LargeURL; break;
                case "Medium": myImageURL = myImage.MediumURL; break;
                case "Original": myImageURL = myImage.OriginalURL; break;
                case "Small": myImageURL = myImage.SmallURL; break;
                case "Thumb": myImageURL = myImage.ThumbURL; break;
                case "Tiny": myImageURL = myImage.TinyURL; break;
                case "XLarge": myImageURL = myImage.XLargeURL; break;
                case "X2Large": myImageURL = myImage.X2LargeURL; break;
                case "X3Large": myImageURL = myImage.X3LargeURL; break;
                default: myImageURL = myImage.TinyURL; break;
            }
            return myImageURL;
        }

        /// <summary>
        /// Returns a list with the Images that are selected in the FlowLayoutPanel
        /// </summary>
        /// <returns></returns>
        private List<SmugMugModel.Image> GetSelectedImagesFromFlwLtPnl()
        {
            List<SmugMugModel.Image> selectedImages = new List<SmugMugModel.Image>();
            int SelectedImagesNumber = 0;
            // Validates that the FlowLayoutPanel has elements and there for Images, if not, there isn't a possibility that something is selected, so it returns null
            if (SelectedAlbumImagesFlwLtPnl.Controls.Count == 0)
            {
                return null;
            }
            foreach (System.Object myObject in SelectedAlbumImagesFlwLtPnl.Controls)
            {
                if (myObject is CustomPictureBox)
                {
                    CustomPictureBox myCustomPictureBox = (CustomPictureBox)myObject;
                    if (myCustomPictureBox.Checked)
                    {
                        selectedImages.Add(myCustomPictureBox.PctrBxImage);
                        SelectedImagesNumber++;
                    }
                }
            }
            // Verify if there are any images to sent. If not, send null.
            if (SelectedImagesNumber > 0)
                return selectedImages;
            else
                return null;
        }

        /// <summary>
        /// Selects or unselects all the images
        /// </summary>
        /// <param name="Checked"></param>
        private void SelectUnselectAllImagesFromFlwLtPnl(bool Checked)
        {
            // Validates that the FlowLayoutPanel has elements and there for Images, if not, there isn't a possibility that something is selected, so it returns null
            if (SelectedAlbumImagesFlwLtPnl.Controls.Count != 0)
            {
                foreach (System.Object myObject in SelectedAlbumImagesFlwLtPnl.Controls)
                {
                    if (myObject is CustomPictureBox)
                    {
                        CustomPictureBox myCustomPictureBox = (CustomPictureBox)myObject;
                        myCustomPictureBox.Checked = Checked;
                    }
                }
            }
        }

        /// <summary>
        /// Get all the albums for the user that's logged in, from SmugMug
        /// </summary>
        /// <returns></returns>
        private List<Album> GetAlbumsForCurrentUser()
        {
            List<Album> CurrentUserAlbumsList = null;
            if (CurrentUser != null)
            {
                try
                {
                    CurrentUserAlbumsList = CurrentUser.GetAlbums();
                }
                catch (SmugMugException sme)
                {
                    MessageBox.Show(sme.Message);
                }
            }
            return CurrentUserAlbumsList;
        }

        /// <summary>
        /// Get images for the selected album from SmugMug
        /// </summary>
        /// <param name="SelectedAlbum"></param>
        /// <returns></returns>
        private List<SmugMugModel.Image> GetImagesForSelectedAlbum(Album SelectedAlbum)
        {
            List<SmugMugModel.Image> SelectedAlbumImagesList = null;
            if (SelectedAlbum != null)
            {
                try
                {
                    SelectedAlbumImagesList = SelectedAlbum.GetImages(true);
                }
                catch (SmugMugException sme)
                {
                    MessageBox.Show(sme.Message);
                }
            }
            return SelectedAlbumImagesList;
        }

        /// <summary>
        /// Get the tree for the current user from SmugMug
        /// </summary>
        /// <returns></returns>
        private List<Category> GetTreeForCurrentUser()
        {
            List<Category> AllCategoriesList = null;
            if (CurrentUser != null)
            {
                try
                {
                    AllCategoriesList = CurrentUser.GetTree();
                }
                catch (SmugMugException sme)
                {
                    MessageBox.Show(sme.Message);
                    AllCategoriesList = null;
                }
            }
            return AllCategoriesList;
        }

        /// <summary>
        /// Adds a new TreeNode to a TreeView
        /// </summary>
        /// <param name="TreeNodeName"></param>
        /// <param name="TreeNodeDestination"></param>
        /// <param name="TreeNodeImageIndex"></param>
        /// <param name="TreeNodeSelectedImageIndex"></param>
        /// <returns></returns>
        private int AddNewTreeNode(string TreeNodeName, TreeNodeCollection TreeNodeDestination, int TreeNodeImageIndex, int TreeNodeSelectedImageIndex)
        {
            TreeNode NewTreeNode = new TreeNode(TreeNodeName);
            NewTreeNode.ImageIndex = TreeNodeImageIndex;
            NewTreeNode.SelectedImageIndex = TreeNodeSelectedImageIndex;
            TreeNodeDestination.Add(NewTreeNode);
            return NewTreeNode.Index;
        }

        /// <summary>
        /// Adds a new TreeNode to a TreeView
        /// </summary>
        /// <param name="TreeNodeName"></param>
        /// <param name="TreeNodeDestination"></param>
        /// <param name="TreeNodeImageIndex"></param>
        /// <param name="TreeNodeSelectedImageIndex"></param>
        /// <param name="TreeNodeColor"></param>
        /// <returns></returns>
        private void AddNewTreeNode(string TreeNodeName, TreeNodeCollection TreeNodeDestination, int TreeNodeImageIndex, int TreeNodeSelectedImageIndex, Color TreeNodeColor)
        {
            TreeNode NewTreeNode = new TreeNode(TreeNodeName);
            NewTreeNode.ImageIndex = TreeNodeImageIndex;
            NewTreeNode.SelectedImageIndex = TreeNodeSelectedImageIndex;
            NewTreeNode.BackColor = TreeNodeColor;
            TreeNodeDestination.Add(NewTreeNode);
            //return NewTreeNode.Index;
        }

        /// <summary>
        /// Populates the current userTreeView with data (categories, their albums and subcategories)
        /// </summary>
        /// <param name="AllCategoriesList"></param>
        private void PopulateUserTreeView(List<Category> AllCategoriesList)
        {
            UserTreeView.Nodes.Clear();
            if (AllCategoriesList != null)
            {
                foreach (Category myCategory in AllCategoriesList)
                {
                    // choose only the categories and subcategories that have albums, to display
                    if ((myCategory.Albums.Count != 0) || (myCategory.SubCategories.Count != 0))
                    {
                        // Add the category to the tree view
                        int CategoryTreeNodeIndex = AddNewTreeNode(myCategory.Name, UserTreeView.Nodes, 0, 1);

                        // Get the albums for the category and add them to the tree view
                        List<Album> myCategoryAlbumsList = myCategory.Albums;
                        if (myCategoryAlbumsList != null)
                        {
                            foreach (Album myAlbum in myCategoryAlbumsList)
                            {
                                AddNewTreeNode(myAlbum.Title, UserTreeView.Nodes[CategoryTreeNodeIndex].Nodes, 4, 5, Color.White);
                            }

                            // Get the subcategories list for the category
                            List<SubCategory> myCategorySubCategoriesList = myCategory.SubCategories;
                            List<SubCategory> SubCategoriesWithAlbums = new List<SubCategory>();
                            foreach (SubCategory mySubCategory in myCategorySubCategoriesList)
                            {
                                if (mySubCategory.Albums.Count != 0)
                                {
                                    // Add the subcategory to the tree view
                                    int SubCategoryTreeNodeIndex = AddNewTreeNode(mySubCategory.Name, UserTreeView.Nodes[CategoryTreeNodeIndex].Nodes, 2, 3);

                                    // Get the albums for the subcategory and add them to the tree view
                                    List<Album> mySubCategoryAlbumsList = mySubCategory.Albums;
                                    foreach (Album myAlbum in mySubCategoryAlbumsList)
                                    {
                                        AddNewTreeNode(myAlbum.Title, UserTreeView.Nodes[CategoryTreeNodeIndex].Nodes[SubCategoryTreeNodeIndex].Nodes, 4, 5, Color.White);
                                    }
                                }
                            }
                        }
                    }
                }
                //UserTreeView.ExpandAll();
            }
        }

        /// <summary>
        /// Make the UnselectBttn, SelectAllBttn buttons visible or invisible
        /// </summary>
        /// <param name="IsVisible"></param>
        private void MakeSelectButtons_In_Visible(bool IsVisible)
        {
            UnselectBttn.Visible = IsVisible;
            SelectAllBttn.Visible = IsVisible;
        }

        public GetSmugMugImages()
        {
            InitializeComponent();
        }

        /// <summary>
        /// Loads the form
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GetSmugMugImages_Load(object sender, EventArgs e)
        {
            // Log in to SmugMug using the UserId and PasswordHash if stored in the registries, otherwise ask for user name and password until you get a good one or a cancel
            if (SmugMugLogInWithHash() == false)
            {
                SmugMugLogIn();
            }

            // Get the category tree for the user and display the categories and subcategories that have albums
            PopulateUserTreeView(GetTreeForCurrentUser());
        }

        /// <summary>
        /// Defines the actions that are performed when double clicking the user tree view
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UserTreeView_DoubleClick(object sender, EventArgs e)
        {
            SelectedAlbumImagesFlwLtPnl.Controls.Clear();

            // Validates that a node is selected, that it is an album
            if ((UserTreeView.SelectedNode != null) && (UserTreeView.SelectedNode.BackColor == Color.White))
            {
                List<Album> CurrentUserAlbumsList = GetAlbumsForCurrentUser();
                if (CurrentUserAlbumsList != null)
                {
                    foreach (Album myAlbum in CurrentUserAlbumsList)
                    {
                        if (myAlbum.Title == UserTreeView.SelectedNode.Text)
                        {
                            //SelectedAlbum = myAlbum;
                            SelectedAlbumImagesFlwLtPnl.Visible = true;
                            List<SmugMugModel.Image> SelectedAlbumImagesList = GetImagesForSelectedAlbum(myAlbum);
                            if (SelectedAlbumImagesList != null)
                            {
                                foreach (SmugMugModel.Image myImage in SelectedAlbumImagesList)
                                {
                                    if (myImage.Hidden == false)
                                    {
                                        CustomPictureBox pb = new CustomPictureBox(myImage);
                                        SelectedAlbumImagesFlwLtPnl.Controls.Add(pb);
                                    }
                                }
                                MakeSelectButtons_In_Visible(true);
                            }
                            else
                            {
                                MakeSelectButtons_In_Visible(false);
                                MessageBox.Show("There are no images in the album!");
                            }
                        }
                    }
                }
                else
                    MessageBox.Show("The user has no albums!");
            }
            else
            {
                MakeSelectButtons_In_Visible(false);
                MessageBox.Show("This is not an album!");
            }
        }

        /// <summary>
        /// Defines the action of the button that selects all the images in the control
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SelectAllBttn_Click(object sender, EventArgs e)
        {
            SelectUnselectAllImagesFromFlwLtPnl(true);
        }

        /// <summary>
        /// Defines the action of the button that unselects all the images in the control
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UnselectBttn_Click(object sender, EventArgs e)
        {
            SelectUnselectAllImagesFromFlwLtPnl(false);
        }

        /// <summary>
        /// Defines the actions that are performed when clicking the Change Current User button
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ChangeCurrentUserBttn_Click(object sender, EventArgs e)
        {
            SmugMugLogIn();
            if (IsAlreadyLogged == false)
            {
                MakeSelectButtons_In_Visible(false);
                SelectedAlbumImagesFlwLtPnl.Visible = false;
                // Get the category tree for the user and display the categories and subcategories that have albums
                PopulateUserTreeView(GetTreeForCurrentUser());
            }
        }

        /// <summary>
        /// Defines the actions that are performed when clicking the Ok button
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OkBttn_Click(object sender, EventArgs e)
        {
            List<SmugMugModel.Image> selectedImages = GetSelectedImagesFromFlwLtPnl();
            if (selectedImages != null)
            {
                ChooseSize cs = new ChooseSize();
                cs.ShowDialog(this);
                if (cs.DialogResult == DialogResult.OK)
                {
                    foreach (SmugMugModel.Image myImage in selectedImages)
                    {
                        String MyImageURL = SetImageURL(cs.SelectedPictureSize, myImage);
                        //<a href="http://www.site.com/photos/name.jpg"><img src="http://www.site.com/photos/name.jpg"></a>
                        if (cs.EmbedPictureLink == false)
                            toSend = string.Format("{0}<IMG src=\"{1}\" />", toSend, MyImageURL);
                        else
                            toSend = string.Format("{0}<A href=\"{1}\" /><IMG src=\"{1}\" /></A>", toSend, MyImageURL);
                    }
                    this.DialogResult = DialogResult.OK;
                }
            }
            else
                MessageBox.Show("Please select at least a picture!");
        }

        /// <summary>
        /// Defines the actions that are performed when clicking the Cancel button
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CancelBttn_Click(object sender, EventArgs e)
        {
            if (CurrentUser == null)
            {
                try
                {
                    CurrentUser.Logout();
                }
                catch (SmugMugException sme)
                {
                    MessageBox.Show(sme.Message);
                }
            }
            this.DialogResult = DialogResult.Cancel;
        }
    }
}